package net.ib.mtalk.network.task;

import net.ib.mntalk.protocol.Common;
import net.ib.mntalk.protocol.Session.AcquireAccessTokenReq;
import net.ib.mntalk.protocol.Session.AcquireAccessTokenRes;
import net.ib.mtalk.constant.HandlerMsgConst;
import net.ib.mtalk.network.TcpEnvelope;
import net.ib.mtalk.network.MethodId.Session;
import net.ib.mtalk.util.MTalkLogWriter;
import android.content.Context;
import android.os.Handler;
import android.os.Message;

public class AcquireAccessTask extends AsyncNetTask {

	private AcquireAccessTokenReq mReq;
	
	public AcquireAccessTask(Context context, Handler handler, AcquireAccessTokenReq req) {
		super(context, handler);
		mReq = req;
	}

	@Override
	protected TcpEnvelope onPreExecute() {		
		TcpEnvelope revelop = new TcpEnvelope.Builder()
		.setMessage(mReq)
		.setMethodId(Session.Authentication.AcquireAccessToken)
		.setType(TcpEnvelope.REQUEST)
		.build();
		return revelop;
	}

	@Override
	protected void onPostExecute(int resultCode, Object sentObject, Object receivedObject) {
		MTalkLogWriter.d("AcquireAccessTask.onPostExecute() resultCode : " + resultCode);
		if (receivedObject == null) {
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_UNKNOWN_ERROR));
			return;
		}
		
		TcpEnvelope resultEnvelope = (TcpEnvelope) receivedObject;
		AcquireAccessTokenRes res = (AcquireAccessTokenRes) resultEnvelope.getMessage();
		
		if(res.getResponseCode() == Common.SUCCESS){
			Message msg = mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_ACQUIRE_ACCESS_SUCCESS);
			msg.obj = res.getAccessToken();
			mUiHandler.sendMessageAtFrontOfQueue(msg);
		} else{
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_ACQUIRE_ACCESS_FAIL));
		}
	}
}
